package com.tomato.study.jwt.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt拦截器
 *
 * @author lizhifu
 * @date 2022/4/27
 */
public class AuthInterceptor implements HandlerInterceptor {
    private static final String SECRET = "lizhifu";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        Map<String, Object> result = new HashMap<>();
        try {
            // 校验token,校验失败会抛出异常
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (TokenExpiredException e) {
            result.put("code", "500");
            result.put("msg", "token已过期");
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "token无效");
        }
        response.setContentType("application/json;charset=UTF-8");
        // 返回json
        response.getWriter().println(result);
        return false;
    }
}
